package com.admin_system.controller;

import com.admin_system.entity.Notice;
import com.admin_system.service.NoticeService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公告控制器
 * 处理公告相关的请求
 */
@RestController
@RequestMapping("/api/notice")
@Slf4j
public class NoticeController {
    
    @Autowired
    private NoticeService noticeService;
    
    /**
     * 获取公告列表
     */
    @GetMapping("/list")
    public ResponseEntity<List<Notice>> getNoticeList() {
        List<Notice> notices = noticeService.getAllNotices();
        return ResponseEntity.ok(notices);
    }
    
    /**
     * 获取公告详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getNoticeDetail(@PathVariable("id") Long id) {
        Notice notice = noticeService.getNoticeById(id);
        if (notice == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(Map.of("success", false, "message", "公告不存在"));
        }
        return ResponseEntity.ok(notice);
    }
    
    /**
     * 添加公告 (仅管理员)
     */
    @PostMapping("/add")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ResponseEntity<?> addNotice(@RequestBody Notice notice) {
        try {
            // 获取当前登录用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            
            boolean result = noticeService.addNotice(notice, username);
            
            if (result) {
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "公告添加成功",
                        "id", notice.getId()
                ));
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(Map.of("success", false, "message", "公告添加失败"));
            }
        } catch (Exception e) {
            log.error("添加公告失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("success", false, "message", "服务器错误：" + e.getMessage()));
        }
    }
    
    /**
     * 更新公告 (仅管理员)
     */
    @PutMapping("/update/{id}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ResponseEntity<?> updateNotice(@PathVariable("id") Long id, @RequestBody Notice notice) {
        try {
            // 检查公告是否存在
            Notice existingNotice = noticeService.getNoticeById(id);
            if (existingNotice == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(Map.of("success", false, "message", "公告不存在"));
            }
            
            // 设置ID以确保更新正确的记录
            notice.setId(id);
            
            // 保留原始的发布时间和发布者
            notice.setPublishTime(existingNotice.getPublishTime());
            notice.setPublishUser(existingNotice.getPublishUser());
            
            boolean result = noticeService.updateNotice(notice);
            
            if (result) {
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "公告更新成功"
                ));
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(Map.of("success", false, "message", "公告更新失败"));
            }
        } catch (Exception e) {
            log.error("更新公告失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("success", false, "message", "服务器错误：" + e.getMessage()));
        }
    }
    
    /**
     * 删除公告 (仅管理员)
     */
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ResponseEntity<?> deleteNotice(@PathVariable("id") Long id) {
        try {
            // 检查公告是否存在
            Notice notice = noticeService.getNoticeById(id);
            if (notice == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(Map.of("success", false, "message", "公告不存在"));
            }
            
            boolean result = noticeService.deleteNotice(id);
            
            if (result) {
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "公告删除成功"
                ));
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(Map.of("success", false, "message", "公告删除失败"));
            }
        } catch (Exception e) {
            log.error("删除公告失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("success", false, "message", "服务器错误：" + e.getMessage()));
        }
    }
} 